package org.docmanagement.actions;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.docmanagement.commons.TodoComparator;
import org.docmanagement.commons.service.ServiceException;
import org.docmanagement.commons.struts.CommonAction;
import org.docmanagement.data.TodoItem;
import org.docmanagement.forms.IdForm;
import org.docmanagement.forms.TodoForm;
import org.docmanagement.services.CategoryException;
import org.docmanagement.services.KeywordException;
import org.docmanagement.services.TodoException;

/**
 * Created on 11 oct. 2004
 * 
 * @author Mektoub
 */
public class TodoAction extends CommonAction
{
	protected TodoComparator todoComparator = new TodoComparator();
    /**
     * @see org.docmanagement.commons.struts.BaseDispatchAction#createMethodMap()
     */
    protected void createMethodMap()
    {
        methodMap = new HashMap<String, String>();
        methodMap.put("Lister", "list");
        methodMap.put("PrepareAdd", "prepareAdd");
        methodMap.put("Ajouter", "add");
        methodMap.put("Modifier", "get");
        methodMap.put("Sauver", "update");
        methodMap.put("Supprimer", "delete");
    }

    /**
     * @see org.docmanagement.actions.DataManagerAction#add(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward prepareAdd(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
    	addTodoCategoryList(request);
    	return mapping.findForward(ADD);
    }

    protected void addTodoStatusList(HttpServletRequest request) throws TodoException
    {
    	List<LabelValueBean> outputList = new LinkedList<LabelValueBean>();
		outputList.add(new LabelValueBean(TODO_STARTED_STRING, TODO_STARTED+""));
		outputList.add(new LabelValueBean(TODO_FINISHED_STRING, TODO_FINISHED+""));
    	request.setAttribute("statusList", outputList);
	}

    protected void addTodoCategoryList(HttpServletRequest request) throws TodoException
    {
    	List<String> categories = getTodoService().getCategoryList();
    	List<LabelValueBean> outputList = new LinkedList<LabelValueBean>();
    	for (Iterator<String> iter = categories.iterator(); iter.hasNext();) {
			String categoryName = (String) iter.next();
			LabelValueBean bean = new LabelValueBean(categoryName, categoryName);
			outputList.add(bean);
		}
    	request.setAttribute("categories", outputList);
	}

	/**
     * @see org.docmanagement.actions.DataManagerAction#add(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward add(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        TodoForm todoForm = (TodoForm) form;
        todoForm.setStatus(TODO_STARTED);
        log.debug("Adding todo: " + todoForm.toString());
        getTodoService().add(toTodoItem(todoForm));
        addTodoList(request);
        return mapping.findForward(SHOW);
    }
    /**
     * @see org.docmanagement.actions.DataManagerAction#get(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward get(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        IdForm id = (IdForm) form;
        addTodoStatusList(request);
        addTodoCategoryList(request);
        addTodo(request, id.getId());
        return mapping.findForward(EDIT);
    }
    /**
     * @see org.docmanagement.actions.DataManagerAction#update(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
    	TodoForm todoForm = (TodoForm) form;
        getTodoService().update(toTodoItem(todoForm));
        addTodoList(request);
        return mapping.findForward(SHOW);
    }
    /**
     * @see org.docmanagement.actions.DataManagerAction#delete(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        TodoForm todoForm = (TodoForm) form;
        if (todoForm.getStatus() != TODO_FINISHED)
        {
        	log.info("Updating Toto Status --> FINISHED");
        	TodoItem item = (TodoItem) getTodoService().findById(todoForm.getId());
        	item.setStatus(TODO_FINISHED);
        	getTodoService().update(item);
        }
        else
        {
        	getTodoService().removeById(todoForm.getId());
        }
        addTodoList(request);
        return mapping.findForward(SHOW);
    }
    /**
     * @see org.docmanagement.actions.DataManagerAction#delete(org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        addTodoList(request);
        return mapping.findForward(SHOW);
    }
    /**
     * @param request
     * @param id
     * @throws KeywordException
     */
    protected void addTodo(HttpServletRequest request, Integer id) throws ServiceException
    {
    	TodoItem todoItem = (TodoItem) getTodoService().findById(id);
        TodoForm todoForm = fromTodoItem(todoItem);
        request.setAttribute(TODO_KEY, todoForm);
    }
    /**
     * @param request
     * @throws CategoryException
     */
    protected void addTodoList(HttpServletRequest request) throws ServiceException
    {
        List<TodoItem> todoItems = getTodoService().findAll();
        
        List<TodoForm> forms = new LinkedList<TodoForm>();
        for (Iterator<TodoItem> iter = todoItems.iterator(); iter.hasNext();)
        {
        	TodoItem todoItem = iter.next();
            forms.add( fromTodoItem(todoItem) );
        }
        Collections.sort(forms, todoComparator);
        request.setAttribute(TODO_LIST_KEY, forms);
    }
    /**
     * @param keywordForm
     * @return
     */
    public TodoForm fromTodoItem(TodoItem todoItem)
    {
        TodoForm todoForm = new TodoForm();
        if (todoItem.getId() != null)
        	todoForm.setId(todoItem.getId());
        if (StringUtils.isNotEmpty(todoItem.getText()))
        	todoForm.setText(todoItem.getText());
        if (StringUtils.isNotEmpty(todoItem.getCategory()))
        	todoForm.setCategory(todoItem.getCategory());
        if (todoItem.getStatus() != -1)
        	todoForm.setStatus(todoItem.getStatus());
        return todoForm;
    }
    /**
     * @param todoForm
     * @return
     */
    public static TodoItem toTodoItem(TodoForm todoForm)
    {
    	TodoItem todoItem = new TodoItem();
        if (todoForm.getId() != null)
        	todoItem.setId(todoForm.getId());

        if (StringUtils.isNotEmpty(todoForm.getText()))
        	todoItem.setText(todoForm.getText());

        if (StringUtils.isEmpty(todoForm.getNewCategory()))
        {
            if (StringUtils.isNotEmpty(todoForm.getCategory()))
            	todoItem.setCategory(todoForm.getCategory());
        }
        else
        {
        	todoItem.setCategory(todoForm.getNewCategory());
        }

        if (todoForm.getStatus() != -1)
        	todoItem.setStatus(todoForm.getStatus());

        return todoItem;
    }
}